import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {SocketService} from "../services/socket.service";

@Injectable()
export class MainGuard implements CanActivate {
  constructor(private socketService: SocketService) {
  }

  canActivate(next: ActivatedRouteSnapshot,
              state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
    if (this.socketService.ws) {
      this.socketService.wsClose();
    }
    this.socketService.wsConnect(loginInfo.login_account, loginInfo.login_pwd)
      .subscribe(
        data => {
          this.socketService.wsMsg(data);
        },
        error => {
          console.log(error)
        },
        () => {
          console.log('webSocket服务连接已经断开')
        }
      );
    return true;
  }
}
